package com.wxzz.elearing.file.util;

import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.MultimediaInfo;
import ws.schild.jave.MultimediaObject;

import java.io.File;
import java.util.UUID;

@Slf4j
public class ObsFileUtil {

    private static ImmutableList<String> videoSuffixList = ImmutableList.of("mp4", "mov", "avi", "mkv", "m4v", "wmv",
            "asf", "asx", "rm", "rmvb", "3gp", "dat", "flv", "vob");

    /**
     * 获取视频时长 * @param file 视频文件
     *
     * @return 时长（秒）
     */
    public static int getVideoDuration(MultipartFile file) {
        int duration = 0;
        File tempFile = null;
        try {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), "." + FilenameUtils.getExtension(file.getOriginalFilename()));
            file.transferTo(tempFile);
            MultimediaObject multimediaObject = new MultimediaObject(tempFile);
            MultimediaInfo info = multimediaObject.getInfo();
            duration = (int) Math.ceil((double) info.getDuration() / 1000);
        } catch (Exception e) {
            log.error("获取视频时长失败", e);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
        return duration;
    }

    /**
     * 判断文件是否是视频 * @param file 文件
     *
     * @return 是否是啊视频
     */
    public static boolean isVideo(MultipartFile file) {
        return videoSuffixList.contains(FilenameUtils.getExtension(file.getOriginalFilename()));
    }

}
